/*
 * @Author: your name
 * @Date: 2021-10-06 17:22:22
 * @LastEditTime: 2021-10-12 16:32
 * @LastEditors: xinyang3
 * @Description: blog_doc collect crud
 * @FilePath: \blog\bgmg\request\blog_doc.js
 */
// const client = require('./client');
const format = require('../util/date-fmt');
const docFile = require('../util/doc-file');
const { ObjectID } = require('mongodb');

const dbName = 'blogs';
const collectionName = 'blog_doc';

/**
 * @description: 获取连接
 */
async function connectCollect() {
  const connect = await client.connect();
  const collection = await client.db(dbName).collection(collectionName);
  return { connect, collection };
}

/**
 * @description: 为对象添加属性
 * @param {*} obj
 * @param {*} key
 * @param {*} value
 * @return {*}
 */
function objectSetKey(obj, key, value) {
  obj && key ? (obj[key] = value || '') : null;
}

async function insert(data) {
  const { blog_id, file, user = 'admin' } = data;
  const date = format(new Date(), 'yyyy-MM-dd HH:mm:ss');
  const cnt = await client.connect();
  const { path, fileName } = await docFile.saveFile(file);
  const collection = await client.db(dbName).collection(collectionName);
  const result = await collection.insertOne({
    blog_id,
    file_name: fileName,
    path,
    create_user: user,
    update_user: user,
    create_date: date,
    update_date: date
  });
  await cnt.close();
  return { insertedId: result.insertedId, fileName };
}

async function insertOne(data) {
  const { connect, collection } = await connectCollect();
  const {
    user = 'admin',
    state,
    file_path,
    file_name,
    file_origin_name
  } = data;
  const date = format(new Date(), 'yyyy-MM-dd HH:mm:ss');
  const result = await collection.insertOne({
    file_name,
    file_origin_name,
    file_path,
    state,
    create_user: user,
    update_user: user,
    create_date: date,
    update_date: date
  });
  console.debug(`collection blog_doc has insert one. ${result.insertedId}`);
  await connect.close();
  return result;
}

async function query(data) {
  const { connect, collection } = await connectCollect();

  const {
    file_name,
    update_date,
    sortField = 'update_date',
    order = -1,
    page = 1,
    pageSize = 10
  } = data;

  const sortColumn = {};
  objectSetKey(sortColumn, sortField, order);

  const filter = [{}];
  if (file_name) {
    filter.push({ file_name: { $regex: new RegExp(`${fileName}`) } });
  }
  if (update_date) {
    filter.push({ update_date: { $regex: new RegExp(`^${date}`) } });
  }
  const result = await collection
    .find({
      $and: filter
    })
    .limit(Number(pageSize))
    .skip(page - 1)
    .sort(sortColumn)
    .toArray();
  await connect.close();
  return result;
}

async function queryOne({ _id }) {
  const { connect, collection } = await connectCollect();

  const result = await collection.findOne({
    _id: { $eq: ObjectID(_id) }
  });
  await connect.close();
  return result;
}

async function updateOne(data) {
  const { connect, collection } = await connectCollect();
  const { _id, state, user, file_name, file_origin_name, file_path } = data;
  const date = format(new Date(), 'yyyy-MM-dd HH:mm:ss');

  const colect = {};
  Object.assign(colect, {
    file_name,
    file_origin_name,
    file_path,
    update_user: user,
    update_date: date
  });
  objectSetKey(colect, 'state', state);

  const result = await collection.updateOne(
    {
      _id: { $eq: ObjectID(_id) }
    },
    [
      {
        $set: colect
      }
    ]
  );
  console.debug(`blog_doc is updated modifiedCount ${result.modifiedCount}`);
  await connect.close();
  return result;
}

async function deleteOne({ _id }) {
  const { connect, collection } = await connectCollect();

  const result = await collection.deleteOne({
    _id: { $eq: ObjectID(_id) }
  });
  console.debug(`blog_doc is deleted count ${result.deletedCount}`);
  await connect.close();
  return result;
}

module.exports.insert = insert;
module.exports.insertOne = insertOne;
module.exports.query = query;
module.exports.queryOne = queryOne;
module.exports.updateOne = updateOne;
module.exports.deleteOne = deleteOne;
